SOURCES := $(patsubst %.c,%.o,$(shell find . -name "*.c"))
SOURCES += $(patsubst %.s,%.o,$(shell find . -mindepth 2 -name "*.s"))
CNAUGHT := c0.o
HEADERS := $(shell find inc -name "*.h")
BUILDDIR := $(PWD)/src
SUBDIR	:= libc
STATIC	:= libc.a
SHARED	:= libc.so
#CFLAGS	= -pipe -Wall -Wextra -pedantic -std=c99 -Werror
#CFLAGS	+= -Wpointer-arith -Wwrite-strings
#CFLAGS	+= -Wno-unused-parameter -Wno-unused-function
CFLAGS	+= -O3 -fomit-frame-pointer
CFLAGS	+= -ffreestanding -fPIC
CFLAGS  += -I$(BUILDDIR)/include/libcmos/inc/ -fPIC
AS := nasm
ASFLAGS := -felf

.PHONY: headers_dir $(HEADERS) clean

all: $(STATIC) $(CNAUGHT) $(SHARED)

headers_dir:
	@ echo " MKDIR	" $(BUILDDIR)/include/libcmos/inc/rho
	@ mkdir -p $(BUILDDIR)/include/libcmos/inc/rho
	@ echo " MKDIR	" $(BUILDDIR)/include/libcmos/inc/sys
	@ mkdir -p $(BUILDDIR)/include/libcmos/inc/sys

$(HEADERS): headers_dir
	@ echo " CP	" $(SUBDIR)/$@ "->" $(BUILDDIR)/include/libcmos/$@
	@ cp $@ $(BUILDDIR)/include/libcmos/$@

$(STATIC): $(HEADERS) $(SOURCES)
	@ echo " AR	" $(SUBDIR)/$(STATIC)
	@ $(AR) $(ARFLAGS) $(STATIC) $(SOURCES)
	@ echo " CP	" $(SUBDIR)/$(STATIC) "->" $(BUILDDIR)/lib
	@ cp $(STATIC) $(BUILDDIR)/lib

$(CNAUGHT): $(patsubst %.o,%.s,$(CNAUGHT))
	@ echo " AS	" $(SUBDIR)/$<
	@ $(AS) $(ASFLAGS) $<
	@ echo " CP	" $(SUBDIR)/$(CNAUGHT) "->" $(BUILDDIR)/lib
	@ cp $(CNAUGHT) $(BUILDDIR)/lib

$(SHARED): $(HEADERS) $(SOURCES) $(CNAUGHT)
	@ echo " LD	" $(SUBDIR)/$(SHARED)
	@ $(LD) $(LDFLAGS) -shared $(SOURCES) -o $(SHARED) -soname $(SHARED).1
	@ echo " CP	" $(SUBDIR)/$(SHARED) "->" $(BUILDDIR)/lib
	@ cp $(SHARED) $(BUILDDIR)/lib

%.o: %.s
	@ echo " AS	" $(SUBDIR)/$<
	@ $(AS) $(ASFLAGS) $<

%.o: %.c
	@ echo " CC	" $(SUBDIR)/$<
	@ $(CC) $(CFLAGS) -c $< -o $@

clean:
	@ rm -f $(SHARED) $(CNAUGHT) $(STATIC) $(SOURCES)

